package server

import (
	"context"
	"os"
	"time"
	"xr-game-server/core/constants/cmd"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/event"
	"xr-game-server/core/httpserver"
	"xr-game-server/core/push"
	"xr-game-server/dao/serverdao"
	"xr-game-server/dto/serverdto"
	"xr-game-server/entity"
	"xr-game-server/gameevent"
)

func Page(ctx context.Context, req *serverdto.CMSServerReq) (res *httpserver.CMSQueryResp, err error) {
	return httpserver.NewCMSQueryResp(serverdao.Page(req)), nil
}

func GetServer(ctx context.Context, req *serverdto.ServerReq) (res *serverdto.ServerRes, err error) {
	cache := serverdao.GetAllServer()
	rets := make([]*entity.Server, common.Zero)
	for _, v := range cache {
		if v.Status != common.ServerClose {
			rets = append(rets, v)
		}
	}
	return serverdto.NewServerRes(cache), nil
}

func SaveServer(ctx context.Context, req *serverdto.SaveServerReq) (res bool, err error) {
	serverdao.Save(req.Data)
	serverdao.InitServer()
	//服务器配置发生变化
	event.Pub(gameevent.ServerEditEvent, gameevent.NewServerEditEventData())
	return true, nil
}

// CanEnter 判断服务器是否可以进入
func CanEnter(server *entity.Server) bool {
	if server.Status == common.ServerNormal {
		return true
	}
	if server.Status == common.ServerOpenTime && time.Now().After(*server.OpenTime) {
		return true
	}
	return false
}

func OpenServer(ctx context.Context, req *serverdto.OpenServerReq) (bool, error) {
	serverdao.UpdateNormal()
	serverdao.InitServer()
	push.BroadcastNonData(cmd.OpenServer)
	return true, nil
}

func CloseServer(ctx context.Context, req *serverdto.CloseServerReq) (bool, error) {
	serverdao.UpdateClose()
	serverdao.InitServer()
	// 推送关闭服务器
	push.BroadcastNonData(cmd.CloseServer)
	return true, nil
}

func broadcastCloseServer(os os.Signal) {
	push.BroadcastNonData(cmd.CloseServer)
}

func MergeServer(ctx context.Context, req *serverdto.MergeServerReq) (bool, error) {
	if req.ZoneId == common.Zero {
		return false, nil
	}
	serverdao.MergeServer(req)
	serverdao.InitServer()
	//服务器配置发生变化
	event.Pub(gameevent.ServerEditEvent, gameevent.NewServerEditEventData())
	return true, nil
}
